'''
Created on Jan 18, 2010

@author: madsk
'''

from PIL import Image
import os
from common import MultiImage
import logging

class ImageLoader(object):
    SUPPORTED_FORMATS = "jpg"
    
    def __init__(self, path, desired_size):
        super(ImageLoader, self).__init__()
        self._path = path
        self._desired_size = desired_size
        self._pos = -1
        self._images = []
        self._current = None
        
    def scan(self):
        """
        Scans the given path for jpg images and adds them to the image browser.
        @raise OSError: If the path is invalid.  
        @raise IOError: If the initial loading of the first image fails.
        @rtype: (int, str)
        @return: A status code, status message tuple. 0 means successful.
        """
        dir_contents = os.listdir(self._path)
        self._images = []
        for image_file in dir_contents:
            if image_file[-3:].lower() in ImageLoader.SUPPORTED_FORMATS:
                self._images.append(self._path + '/' + image_file)
        
        if len(self._images) != 0:
            # Load in the first image.
            self._pos = 0
            try:
                self._current = MultiImage(self._images[self._pos], self._desired_size)
            except Exception, e:
                self._current = None
                logging.getLogger('ImageLoader').error('Error loading image.', exc_info=True)
            return (0, "Found %i images."%(len(self._images)))    
        else:
            return (1, "No images found in path.")
        
    def has_next(self):
        return self._pos < len(self._images) - 1
    
    def next(self):
        # Load the next image and return its data.
        if self._pos < len(self._images) - 1:
            self._pos += 1
            try:
                if self._current == None:
                    self._current = MultiImage()
                self._current.loadFromFile(self._images[self._pos], self._desired_size)
            except Exception, e:
                self._current = None
                logging.getLogger('ImageLoader').error('Error loading image.', exc_info=True)
        return self.current()
    
    def has_previous(self):
        return self._pos > 0
    
    def previous(self):
        # Load the previous image and return its data.
        if self._pos > 0:
            self._pos -= 1
            try:
                if self._current == None:
                    self._current = MultiImage()
                self._current.loadFromFile(self._images[self._pos], self._desired_size)
            except Exception, e:
                self._current = None
                print e.args
        return self.current()
        
    def has_current(self):
        return self._pos != -1
        
    def current(self):
        # Returns the current pixmap image.
        pixmap = None
        if self._current != None:
            pixmap = self._current.pixmap
        return (self._images[self._pos], pixmap)
    
    def current_multi_image(self):
        # Returns the current MultiImage instance.
        return self._current
